package cn.com.digitalnet.ad.util;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.Cache;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.jpa.HibernateEntityManagerFactory;
import org.springframework.stereotype.Component;

/**
 * jpa和hibernate使用的工具类
 * @author qidafang
 */
@Component
public class JpaUtil {

	/**
	 * 注入持久化上下文，jpa的entitymanager作用相当于hibernate的session
	 */
	@PersistenceContext
	private EntityManager em;

    /** 
     * 清空一级缓存 
     */  
    public void clearLevel1Cache() {  
        em.clear();  
    }

    /**
     * 清空二级缓存
     */
    public void clearLevel2Cache(){  
        Cache cache = getCache();
        cache.evictEntityRegions();
        cache.evictCollectionRegions();
        cache.evictDefaultQueryRegion();
        cache.evictQueryRegions();
        cache.evictNaturalIdRegions();
    }  
    
	/**
	 * 获得hibernate的session
	 */
	public Session getSession(){
		return (Session)em.getDelegate();
	}
	
    /** 
     * 获得hibernate的sessionfactory
     */  
    public SessionFactory getSessionFactory() {  
        return ((HibernateEntityManagerFactory)em.getEntityManagerFactory()).getSessionFactory();  
    }  

    /**
     * 获得hibernate的二级缓存
     */
    public Cache getCache() {  
    	return getSessionFactory().getCache();  
    }
    
    public EntityManager getEntityManager(){
    	return em;
    }
}
